<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\enum\Questionnaire as QEnum;
use app\common\service\Question as QService;
use app\admin\model\QuestionFormat as FormatModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Session;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class QuestionCate extends Backend
{
    
    /**
     * QClass模型对象
     * @var \app\admin\model\QClass
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\QClass;

        Session::set('admin_group_arr',$this->auth->getGroupIds());

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    
                    ->where($where)
                    ->where('delete_time','=',0)
                    ->where('uid','=',$this->auth->id)
                    ->order($sort, $order)
                    ->paginate($limit);
//print_r($list);exit;
            foreach ($list as $row) {
                
                $row->visible(['qid','title','format','available','show_mode',
                    'full_mark','pass_mark','count','code_url','header_note','create_time','uid']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        // dump( \think\Session::get('admin'));
        // dump( $this->auth->getGroupIds());
        
        $data = QService::getQuestionnaireClassList();
         //dump($data);die;
        $mode = QEnum::getMarkShowMode();
        
        // return $this->fetch('list', ['data' => $data, 'mode' => $mode]);
        return $this->view->fetch('list', ['data' => $data, 'mode' => $mode,'request' => \think\Request::instance()]);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $params['uid'] = $this->auth->id;
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    public function del($ids = ""){
       
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where(['q_class_id'=>$ids])->update(['delete_time'=>time()]);
        // FormatModel::where(['q_class_id'=>$ids])->update(['delete_time'=>time()]);
        $this->success();
    }

    public function statis()
    {   
        $qid = input('qid');
        
        $info = db('child_q_format')->where(['id'=>$qid])->find();
        $info['format'] = json_decode($info['format'],true);
        
        $count = db('child_q_data')->where(['qid'=>$qid])->count();
       
        return $this->view->fetch('statis', ['info'=>$info,'count'=>$count]);
    }  

    public function statisExcel()
    {   
        $qid = input('qid');
        
        $info = db('child_q_format')->where(['id'=>$qid])->find();
        $info['format'] = json_decode($info['format'],true);
        
        $count = db('child_q_data')->where(['qid'=>$qid])->count();
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $row = 2;
        foreach($info['format'] as $i=> $vo){
           
            $dataCol = 'A';
            
            if($vo['type'] == 0) {
                $sheet->setCellValue($dataCol . $row,($i+1).'、' .$vo['title'].'(单选题)');
                // $sheet->mergeCells('A'.$row.':H'.$row);
                $dataCol++;
                $row++;
                foreach($vo['option'] as $i0 => $op){
                    $total = statisQustionByChose($info['qid'],$i,0,$i0);
                    $num = getNumRatio($total,$count);
                    $dataCol = 'A';
                    $sheet->setCellValue($dataCol . $row, $op);
                    $dataCol++;
                    $sheet->setCellValue($dataCol . $row,'遐择数:'. $total);
                    $dataCol++;
                    $sheet->setCellValue($dataCol . $row,'占比数:'. $num.'%');
                    $dataCol++;
                    $row++;
                } 
                $row++;
            }

            if($vo['type'] == 1) {
                $sheet->setCellValue($dataCol . $row, ($i+1).'、' .$vo['title'].'(多選題)');
                // $sheet->mergeCells('A'.$row.':H'.$row);
                $dataCol++;
                $row++;
                foreach($vo['option'] as $i1 => $op1){
                    $total = statisQustionByChose($info['qid'],$i,1,$i1);
                    $num = getNumRatio($total,$count);
                    $dataCol = 'A';
                    $sheet->setCellValue($dataCol . $row, $op1);
                    $dataCol++;
                    $sheet->setCellValue($dataCol . $row,'遐择数:'. $total);
                    $dataCol++;
                    $sheet->setCellValue($dataCol . $row,'占比数:'. $num.'%');
                    $dataCol++;
                    $row++;
                } 
                $row++;
            }

            if($vo['type'] == 6) {
                $sheet->setCellValue($dataCol . $row, ($i+1).'、' .$vo['title'].'(跳題)');
                // $sheet->mergeCells('A'.$row.':H'.$row);
                $dataCol++;
                $row++;
                foreach($vo['option'] as $i6 => $op6){
                    $total = statisQustionByChose($info['qid'],$i,6,$i6);
                    $num = getNumRatio($total,$count);
                    $dataCol = 'A';
                    $sheet->setCellValue($dataCol . $row, $op6);
                    $dataCol++;
                    $sheet->setCellValue($dataCol . $row,'遐择数:'. $total);
                    $dataCol++;
                    $sheet->setCellValue($dataCol . $row,'占比数:'. $num.'%');
                    $dataCol++;
                    $row++;
                } 
                $row++;
            }

            if($vo['type'] == 2) {
                $sheet->setCellValue($dataCol . $row, ($i+1).'、' .$vo['title'].'(填空题)');
                // $sheet->mergeCells('A'.$row.':H'.$row);
                $dataCol++;
                $row++;
                $arr_str = statisQustionType_2($info['qid'],$i);
                foreach($arr_str as $v){
                    if($dataCol == 'X'){
                        $dataCol == 'A';
                        $row++;
                    }
                    $sheet->setCellValue($dataCol . $row, $v);
                    $dataCol++;

                }
                $row++;
            }

            if($vo['type'] == 3) {
                $sheet->setCellValue($dataCol . $row, ($i+1).'、' .$vo['title'].'(單項填空題)');
                // $sheet->mergeCells('A'.$row.':H'.$row);
                $dataCol++;
                $row++;
                $arr_str = statisQustionType_2($info['qid'],$i,3);
                foreach($arr_str as $v){
                    if($dataCol == 'X'){
                        $dataCol == 'A';
                        $row++;
                    }
                    $sheet->setCellValue($dataCol . $row, $v);
                    $dataCol++;

                }
                $row++;
            }

            if($vo['type'] == 4) {
                $dataCol = 'A';
                $sheet->setCellValue($dataCol . $row, ($i+1).'、' .$vo['title'].'(矩陣單選題)');
                // $sheet->mergeCells('A'.$row.':H'.$row);
                
                $row++;
                foreach($vo['title_list'] as $k=>$ju){
                    $dataCol = 'A';
                    $sheet->setCellValue($dataCol . $row, $ju);
                    // $sheet->mergeCells('A'.$row.':H'.$row);
                    $dataCol++;
                    $row++;
                    foreach($vo['option'] as $i4=>$op4){
                        $total = statisQustionByChose($info['qid'],$i,4,$k,$i4);
                        $num = getNumRatio($total,$count);

                        $dataCol = 'B';
                        $sheet->setCellValue($dataCol . $row, $op4);
                        $dataCol++;
                        $sheet->setCellValue($dataCol . $row,'遐择数:'. $total);
                        $dataCol++;
                        $sheet->setCellValue($dataCol . $row,'占比数:'. $num.'%');
                        $dataCol++;
                        $row++;
                    }
                    
                } 
                $row++;
            }
        }
        $name = $info['title'].'export-'.date('YmdHi');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $name . '.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        //删除清空：
        $spreadsheet->disconnectWorksheets();
    }  
}
